package masterjava.common.state;

import masterjava.common.logging.MasterLogger;
import masterjava.common.util.Util;

import static masterjava.common.state.StateType.*;

/**
 * User: GKislin
 * Date: May 26, 2010
 * <p/>
 * Base class for object with state
 */
public class State {
    protected final MasterLogger logger = MasterLogger.get(getClass());

    private volatile String state;
    protected volatile Throwable exception;
    private volatile StateType stateType = OK;

    public final void clearState() {
        state = null;
        logger.info("Clear state");
        stateType = OK;
        exception = null;
    }

    public final void set(String state, Object... params) {
        setState(OK, state, null, params);
    }

    public final void setWarning(String state, Throwable e, Object... params) {
        setState(WARNING, state, e, params);
    }

    public final void setError(final String state, Throwable e, Object... params) {
        setState(ERROR, state, e, params);
    }

    public final void setState(StateType type, String state, Throwable e, Object... params){
        this.stateType = type;
        this.exception = e;
        this.state = Util.format(state, params);
        logger.log(type.getLoggingLevel(), state, exception);
    }

    public boolean isOk() {
        return stateType == OK;
    }

    public StateType getStateType() {
        return stateType;
    }

    public String getState() {
        return state;
    }

    public Throwable getException() {
        return exception;
    }
}
